<template>
  <div class="admin-page admin-score-components-list">
    <div class="page-header">
      <h1>考核组成管理</h1>
    </div>
    
    <div class="content-layout">
      <!-- 左侧：教学任务列表 -->
      <el-card class="missions-card">
        <template #header>
          <div class="card-header">
            <span>教学任务列表</span>
          </div>
        </template>
        
        <!-- 过滤器 -->
        <TeachingMissionFilter
          :filters="filters"
          :term-options="termOptions"
          :filtered-course-options="filteredCourseOptions"
          :default-term-id="defaultTermId"
          @term-change="handleTermChange"
          @filter-change="handleFilterChange"
          @search="handleSearch"
          @reset="handleReset"
          @update:filters="handleFiltersUpdate"
        />
        
        <!-- 批量操作按钮 -->
        <div class="batch-actions" v-if="filters.termId">
          <el-button 
            type="warning" 
            @click="handleBatchSet"
            :disabled="!filteredMissions.length"
            plain
          >
            <el-icon><Setting /></el-icon> 
            批量设置当前学期考核组成
          </el-button>
        </div>
        
        <!-- 教学任务列表 -->
        <TeachingMissionList
          :missions="paginatedMissions"
          :loading="missionsLoading"
          :selected-mission="selectedMission"
          @mission-select="handleMissionSelect"
        />
        
        <!-- 分页 -->
        <Pagination
          v-if="filteredMissions.length > 0"
          :total="filteredMissions.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @page-change="handlePageChange"
        />
        
        <el-empty 
          v-if="filteredMissions.length === 0" 
          description="暂无教学任务数据"
          :image-size="150"
        />
      </el-card>
      
      <!-- 右侧：考核组成管理 -->
      <el-card class="exam-parts-card">
        <ExamPartsManagement
          :selected-mission="selectedMission"
          :exam-parts="examParts"
          :loading="examPartsLoading"
          @add-exam-part="handleAddExamPart"
          @edit-exam-part="handleEditExamPart"
          @delete-exam-part="handleDeleteExamPart"
          @batch-import="handleBatchImport"
          @batch-copy-success="handleBatchCopySuccess"
        />
      </el-card>
    </div>
    
    <!-- 考核组成编辑对话框 -->
    <ExamPartEditDialog
      v-model:visible="examPartDialogVisible"
      :exam-part="currentExamPart"
      :score-types="scoreTypes"
      :is-edit="isEditMode"
      @submit="handleExamPartSubmit"
    />
    
    <!-- 批量导入对话框 -->
    <ExamPartImportDialog
      v-model:visible="importDialogVisible"
      :selected-mission="selectedMission"
      @import-success="handleImportSuccess"
    />
    
    <!-- 批量设置对话框 -->
    <BatchSetExamPartsDialog
      v-model:visible="batchSetDialogVisible"
      :term-id="filters.termId ? Number(filters.termId) : null"
      @completed="handleBatchSetSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'

// 导入组件
import TeachingMissionFilter from '@/components/teaching-mission/filters/TeachingMissionFilter.vue'
import TeachingMissionList from '@/components/teaching-mission/tables/TeachingMissionList.vue'
import ExamPartsManagement from '@/components/teaching-mission/forms/ExamPartsManagement.vue'
import Pagination from '@/components/common/Pagination.vue'
import ExamPartEditDialog from '@/components/teaching-mission/dialogs/ExamPartEditDialog.vue'
import ExamPartImportDialog from '@/components/teaching-mission/dialogs/ExamPartImportDialog.vue'
import BatchSetExamPartsDialog from '@/components/teaching-mission/dialogs/BatchSetExamPartsDialog.vue'

// 导入API
import { teachingMissionApi } from '@/api/teaching-mission'
import { courseExamPartApi } from '@/api/course-exam-part'
import { termApi } from '@/api/base-data'
import { scoreTypeApi } from '@/api/score-type'

// 响应式数据
const missionsLoading = ref(false)
const examPartsLoading = ref(false)

// 教学任务相关
const missions = ref([])
const selectedMission = ref({})

// 考核组成相关
const examParts = ref([])
const scoreTypes = ref([])

// 基础数据
const terms = ref([])
const defaultTermId = ref(null)

// 过滤和分页
const filters = reactive({
  termId: '',
  courseId: '',
  keyword: ''
})
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框相关
const examPartDialogVisible = ref(false)
const importDialogVisible = ref(false)
const batchSetDialogVisible = ref(false)
const currentExamPart = ref({})
const isEditMode = ref(false)

// 计算属性
const termOptions = computed(() => {
  return terms.value.map(term => ({
    label: term.name,
    value: term.id
  }))
})

const filteredCourseOptions = computed(() => {
  let filteredMissions = missions.value
  
  if (filters.termId) {
    const termIdToMatch = String(filters.termId)
    filteredMissions = filteredMissions.filter(mission => 
      String(mission.termId) === termIdToMatch
    )
  }
  
  const courseMap = new Map()
  filteredMissions.forEach(mission => {
    if (mission.courseId && mission.courseName) {
      courseMap.set(mission.courseId, {
        label: mission.courseName,
        value: mission.courseId
      })
    }
  })
  
  return Array.from(courseMap.values())
})

const filteredMissions = computed(() => {
  let result = missions.value
  
  // 按学期过滤
  if (filters.termId) {
    const termIdToMatch = String(filters.termId)
    result = result.filter(mission => {
      const missionTermId = String(mission.termId)
      return missionTermId === termIdToMatch
    })
  }
  
  // 按课程过滤
  if (filters.courseId) {
    const courseIdToMatch = String(filters.courseId)
    result = result.filter(mission => {
      const missionCourseId = String(mission.courseId)
      return missionCourseId === courseIdToMatch
    })
  }
  
  // 按关键词搜索
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase().trim()
    result = result.filter(mission =>
      (mission.courseName && mission.courseName.toLowerCase().includes(keyword)) ||
      (mission.courseCode && mission.courseCode.toLowerCase().includes(keyword)) ||
      (mission.teacherNames && mission.teacherNames.some(name => 
        name.toLowerCase().includes(keyword)
      )) ||
      (mission.classNames && mission.classNames.some(name => 
        name.toLowerCase().includes(keyword)
      ))
    )
  }
  
  return result
})

const paginatedMissions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredMissions.value.slice(start, end)
})

// 方法
const loadMissions = async () => {
  missionsLoading.value = true
  try {
    const response = await teachingMissionApi.getAllTeachingMissionsList()
    missions.value = response || []
    
    
    // 为每个教学任务获取考核组成信息
    for (const mission of missions.value) {
      try {
        const examPartsResponse = await courseExamPartApi.getExamPartsByTeachingMission(mission.id)
        mission.examParts = examPartsResponse || []
        
        
        // 如果总分等于100分，认为已设置完成
        mission.hasExamParts = totalProportion === 100
        mission.totalProportion = totalProportion
        
      } catch (error) {
        mission.examParts = []
        mission.hasExamParts = false
        mission.totalProportion = 0
      }
    }
    
  } catch (error) {
    ElMessage.error('加载教学任务失败')
  } finally {
    missionsLoading.value = false
  }
}

const loadTerms = async () => {
  try {
    const response = await termApi.getAllTerms()
    terms.value = response || []
    
    // 设置当前学期为默认值
    const currentTerm = terms.value.find(term => term.isCurrent)
    if (currentTerm) {
      defaultTermId.value = currentTerm.id
      filters.termId = currentTerm.id
    }
  } catch (error) {
    ElMessage.error('加载学期数据失败')
  }
}

const loadScoreTypes = async () => {
  try {
    const response = await scoreTypeApi.getAllScoreTypes()
    scoreTypes.value = response || []
  } catch (error) {
    ElMessage.error('加载计分方式失败')
  }
}

const loadExamParts = async (missionId) => {
  if (!missionId) {
    examParts.value = []
    return
  }
  
  examPartsLoading.value = true
  try {
    const response = await courseExamPartApi.getExamPartsByTeachingMission(missionId)
    examParts.value = response || []
  } catch (error) {
    ElMessage.error('加载考核组成失败')
  } finally {
    examPartsLoading.value = false
  }
}

const handleTermChange = (termId) => {
  filters.courseId = ''
  currentPage.value = 1
  selectedMission.value = {}
  examParts.value = []
}

const handleFilterChange = (filterData) => {
  currentPage.value = 1
  selectedMission.value = {}
  examParts.value = []
}

const handleSearch = (keyword) => {
  currentPage.value = 1
}

const handleFiltersUpdate = (newFilters) => {
  Object.assign(filters, newFilters)
}

const handleReset = () => {
  // 重置时保持当前学期，只清空课程和关键词
  filters.courseId = ''
  filters.keyword = ''
  // 如果有默认学期，确保设置为默认学期
  if (defaultTermId.value) {
    filters.termId = defaultTermId.value
  }
  
  currentPage.value = 1
  selectedMission.value = {}
  examParts.value = []
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const handleMissionSelect = (mission) => {
  selectedMission.value = mission
  loadExamParts(mission.id)
}

const handleAddExamPart = () => {
  currentExamPart.value = {
    teachingMissionId: selectedMission.value.id
  }
  isEditMode.value = false
  examPartDialogVisible.value = true
}

const handleEditExamPart = (examPart) => {
  currentExamPart.value = { ...examPart }
  isEditMode.value = true
  examPartDialogVisible.value = true
}

const handleDeleteExamPart = async (examPart) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除考核组成"${examPart.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await courseExamPartApi.delete(examPart.id)
    ElMessage.success('删除成功')
    loadExamParts(selectedMission.value.id)
    loadMissions() // 更新任务列表状态
    
  } catch (error) {
    if (error !== 'cancel') {
      
      // 从错误响应中提取具体的错误信息
      let errorMessage = '删除失败'
      if (error.response && error.response.data) {
        if (error.response.data.message) {
          errorMessage = error.response.data.message
        } else if (error.response.data.details) {
          errorMessage = error.response.data.details
        }
      }
      
      ElMessage.error(errorMessage)
    }
  }
}

const handleBatchImport = () => {
  importDialogVisible.value = true
}

const handleExamPartSubmit = async (formData) => {
  try {
    if (isEditMode.value) {
      await courseExamPartApi.update(currentExamPart.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      await courseExamPartApi.create(formData)
      ElMessage.success('创建成功')
    }
    
    loadExamParts(selectedMission.value.id)
    loadMissions() // 更新任务列表状态
    
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const handleImportSuccess = () => {
  loadExamParts(selectedMission.value.id)
  loadMissions() // 更新任务列表状态
}

const handleBatchSet = () => {
  batchSetDialogVisible.value = true
}

const handleBatchSetSuccess = () => {
  ElMessage.success('批量设置考核组成成功')
  // 重新加载当前选中教学任务的考核组成
  if (selectedMission.value?.id) {
    loadExamParts(selectedMission.value.id)
  }
  // 重新加载教学任务列表以更新状态
  loadMissions()
}

const handleBatchCopySuccess = () => {
  // 重新加载当前选中教学任务的考核组成
  if (selectedMission.value?.id) {
    loadExamParts(selectedMission.value.id)
  }
  // 重新加载教学任务列表以更新状态
  loadMissions()
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadTerms(),
    loadScoreTypes()
  ])
  await loadMissions()
})
</script>

<style scoped>
.admin-page {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.content-layout {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
}

.missions-card {
  width: 60%;
  display: flex;
  flex-direction: column;
}

.missions-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.exam-parts-card {
  width: 40%;
  display: flex;
  flex-direction: column;
}

.exam-parts-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

@media (max-width: 1200px) {
  .content-layout {
    flex-direction: column;
  }
  
  .missions-card,
  .exam-parts-card {
    width: 100%;
  }
}
</style>
